package com.example.service.impl;

import com.example.dao.ProductDao;
import com.example.dao.ReviewDao;
import com.example.entity.Product;
import com.example.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 商品服务实现类
 * @author System
 * @date 2024
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    
    @Autowired
    private ProductDao productDao;

    @Override
    public boolean addProduct(Product product) {
        try {
            // 参数验证
            if (product == null || product.getName() == null || product.getName().trim().isEmpty() ||
                product.getPrice() == null || product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("商品参数不完整或价格无效");
                return false;
            }
            
            product.setStatus(1); // 默认上架
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            
            int result = productDao.insert(product);
            logger.info("添加商品成功: name={}", product.getName());
            return result > 0;
        } catch (Exception e) {
            logger.error("添加商品失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public Product getProductById(Long id) {
        try {
            if (id == null || id <= 0) {
                return null;
            }
            return productDao.selectById(id);
        } catch (Exception e) {
            logger.error("查询商品失败: id={}", id, e);
            return null;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Product> getAllProducts() {
        try {
            List<Product> products = productDao.selectAll();
            for (Product product : products) {
                // product.setAverageRating(reviewDao.getAverageRatingByProductId(product.getId()));
                product.setAverageRating(product.getAverageRating() == null ? 5.0 : product.getAverageRating());
            }
            return products;
        } catch (Exception e) {
            logger.error("查询所有商品失败", e);
            return null;
        }
    }
        @Override
    public List<String> getCategories() {
        try {
            return productDao.selectCategories();
        } catch (Exception e) {
            logger.error("查询分类失败", e);
            return null;
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<Product> getProductsByStatus(Integer status) {
        try {
            if (status == null) {
                return null;
            }
            return productDao.selectByStatus(status);
        } catch (Exception e) {
            logger.error("根据状态查询商品失败: status={}", status, e);
            return null;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Product> getProductsByCategory(String category) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return null;
            }
            return productDao.selectByCategory(category.trim());
        } catch (Exception e) {
            logger.error("根据分类查询商品失败: category={}", category, e);
            return null;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Product> getProductsByKeyword(String keyword) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return getAllProducts();
            }
            return productDao.selectByKeyword(keyword.trim());
        } catch (Exception e) {
            logger.error("根据关键词查询商品失败: keyword={}", keyword, e);
            return null;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Product> getProductsByPage(int page, int size) {
        try {
            if (page < 1 || size < 1) {
                return null;
            }
            int offset = (page - 1) * size;
            return productDao.selectByPage(offset, size,  null);
        } catch (Exception e) {
            logger.error("分页查询商品失败: page={}, size={}", page, size, e);
            return null;
        }
    }
        @Override
    @Transactional(readOnly = true)
    public List<Product> getProductsByPage(int page, int size,String category) {
        try {
            if (page < 1 || size < 1) {
                return null;
            }
            int offset = (page - 1) * size;
            return productDao.selectByPage(offset, size,  category);
        } catch (Exception e) {
            logger.error("分页查询商品失败: page={}, size={}", page, size, e);
            return null;
        }
    }

    @Override
    @Transactional(readOnly = true)
    public int getProductCount() {
        try {
            return productDao.countAll(null);
        } catch (Exception e) {
            logger.error("统计商品数量失败", e);
            return 0;
        }
    }
       @Override
    @Transactional(readOnly = true)
    public int getProductCount(String category) {
        try {
            return productDao.countAll(category);
        } catch (Exception e) {
            logger.error("统计商品数量失败", e);
            return 0;
        }
    }

    @Override
    @Transactional(readOnly = true)
    public int getProductCountByStatus(Integer status) {
        try {
            if (status == null) {
                return 0;
            }
            return productDao.countByStatus(status);
        } catch (Exception e) {
            logger.error("根据状态统计商品数量失败: status={}", status, e);
            return 0;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public int getProductCountByCategory(String category) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return 0;
            }
            return productDao.countByCategory(category.trim());
        } catch (Exception e) {
            logger.error("根据分类统计商品数量失败: category={}", category, e);
            return 0;
        }
    }
    
    @Override
    public boolean updateProduct(Product product) {
        try {
            if (product == null || product.getId() == null) {
                return false;
            }
            
            // 价格验证
            if (product.getPrice() != null && product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("商品价格无效: {}", product.getPrice());
                return false;
            }
            
            product.setUpdateTime(new Date());
            int result = productDao.update(product);
            logger.info("更新商品成功: id={}", product.getId());
            return result > 0;
        } catch (Exception e) {
            logger.error("更新商品失败", e);
            return false;
        }
    }
    
    @Override
    public boolean updateProductStatus(Long id, Integer status) {
        try {
            if (id == null || status == null) {
                return false;
            }
            int result = productDao.updateStatus(id, status);
            logger.info("更新商品状态成功: id={}, status={}", id, status);
            return result > 0;
        } catch (Exception e) {
            logger.error("更新商品状态失败: id={}, status={}", id, status, e);
            return false;
        }
    }
    
    @Override
    public boolean updateProductStock(Long id, Integer stock) {
        try {
            if (id == null || stock == null || stock < 0) {
                return false;
            }
            int result = productDao.updateStock(id, stock);
            logger.info("更新商品库存成功: id={}, stock={}", id, stock);
            return result > 0;
        } catch (Exception e) {
            logger.error("更新商品库存失败: id={}, stock={}", id, stock, e);
            return false;
        }
    }
    
    @Override
    public boolean deleteProduct(Long id) {
        try {
            if (id == null || id <= 0) {
                return false;
            }
            int result = productDao.deleteById(id);
            logger.info("删除商品成功: id={}", id);
            return result > 0;
        } catch (Exception e) {
            logger.error("删除商品失败: id={}", id, e);
            return false;
        }
    }
    
    @Override
    public boolean deleteProducts(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            int result = productDao.deleteByIds(ids);
            logger.info("批量删除商品成功: count={}", result);
            return result > 0;
        } catch (Exception e) {
            logger.error("批量删除商品失败", e);
            return false;
        }
    }
    
    @Override
    public boolean changeProductStatus(Long id, Integer status) {
        try {
            if (id == null || status == null || (status != 0 && status != 1)) {
                return false;
            }
            return updateProductStatus(id, status);
        } catch (Exception e) {
            logger.error("修改商品状态失败: id={}, status={}", id, status, e);
            return false;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isProductExists(String name) {
        try {
            if (name == null || name.trim().isEmpty()) {
                return false;
            }
            
            List<Product> products = productDao.selectAll();
            if (products == null || products.isEmpty()) {
                return false;
            }
            
            return products.stream().anyMatch(product -> name.trim().equals(product.getName()));
        } catch (Exception e) {
            logger.error("检查商品是否存在失败: name={}", name, e);
            return false;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Product> getAvailableProducts() {
        try {
            return productDao.selectByStatus(1); // 状态为1表示上架
        } catch (Exception e) {
            logger.error("获取可用商品列表失败", e);
            return null;
        }
    }
}